package zrweb;

import java.io.DataOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Login
{
	private Connection connect = null;
	private PreparedStatement ps = null;
	
	public void getLogin(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		// get the username and password
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// connect to database to check whether there are records in the database
		ConnDB conndb = new ConnDB();
		// to account how many rows in the database satisfy the conditions
		int rowCount = 0;
		// NOTE: string -> varchar for posrgresql query by using ''
		String loginSQL = "select * from userinfor where username='" + username + "' and passwords='" + password + "'";
		
		try
		{
			connect = conndb.getConn();
			Statement stmt = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); 
			ResultSet rset = stmt.executeQuery(loginSQL); 
			/*
			 * jump to the last row for counting
			 * if rowCount = 1, which means there are one list satisfy the query of username and password at the same time
			 * if rowCount = 0, ...
			 * */
			rset.last(); 
			rowCount = rset.getRow();	
			stmt.close();
			rset.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			ConnDB.releaseConnection(connect);
		}
		// give feedback on whether can login or not for Android mobile
		DataOutputStream dos = new DataOutputStream(response.getOutputStream());
		if (rowCount == 1)
		{
			dos.writeUTF("Succeed");
			/*
			 * the purpose of using onservice column is that when sending traffic jam report, only users who are online
			 * for service will be considered, which would highly increase the performance when millions of people are
			 * participates.
			 * */
			String updateSQL = "update userinfor set onservice = TRUE where username='" + username + "' and passwords='" + password + "'";
			try 
			{
				connect = conndb.getConn();
				ps = connect.prepareStatement(updateSQL);
				ps.executeUpdate();
			} 
			catch (SQLException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finally
			{
				ConnDB.releaseConnection(connect);
			}
		}
		else
		{
			dos.writeUTF("Failed");
		}
	}
}
